import { login, getInfo } from '@/api/user'
import { getToken, getUserId, setToken, setUserId, removeToken, removeUserId } from '@/utils/auth'
import { resetRouter } from '../../router'
import { removeEntSpaceId, removeSpaceId } from '../../../../utils/auth'

const state = {
  token: getToken(),
  userId: getUserId(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const data = response.result
        commit('SET_TOKEN', data.authToken)
        commit('SET_USERID', data.userId)
        setToken(data.authToken)
        setUserId(data.userId)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.userId).then(response => {
        const data = response.result
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        let roles = []
        if (data.roleList && data.roleList.length > 0) {
          roles = data.roleList.map(item => item.roleCode)
        } else {
          roles = ['proAdmin']
        }
        const name = data.username
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('请联系管理员，给该用户设置角色权限')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', data.picture)
        resolve({ roles, name })
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_USERID', '')
      commit('SET_ROLES', [])
      removeToken()
      removeUserId()
      resetRouter()
      removeEntSpaceId()
      removeSpaceId()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
      window.location.href = '/admin/login'
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERID', '')
      commit('SET_ROLES', [])
      removeToken()
      removeUserId()
      resetRouter()
      removeEntSpaceId()
      removeSpaceId()
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
